<template>
  <div class="changePassword">
    <div class="changpasswordBox">
      <el-form
        class="login-box1"
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="100px"
      >
        <h2 class="login-title">修改密码</h2>
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            auto-complete="off"
            placeholder="请输入用户名"
            v-model="loginForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="原密码" prop="oldpassword">
          <el-input
            type="password"
            show-password
            auto-complete="off"
            placeholder="请输入原密码"
            v-model="loginForm.oldpassword"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input
            type="password"
            show-password
            auto-complete="off"
            placeholder="请设置新密码"
            v-model="loginForm.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
          <el-input
            type="password"
            show-password
            auto-complete="off"
            placeholder="请确认新密码"
            v-model="loginForm.password2"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="PasswordBtn">
        <el-button type="primary" @click.prevent="handleLogin"> 确认修改 </el-button>
        <el-button type="primary" @click="resetForm"> 返回登录 </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const loginFormRef = ref(null)
const loginForm = ref({
  username: '',
  oldpassword: '',
  password: '',
  password2: '',
})

// 定义 validatePass2 函数
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请确认新密码'))
  } else if (value !== loginForm.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  oldpassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  password: [
    { required: true, message: '请设置新密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' },
  ],
  password2: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' },
  ],
}

const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      // 先进行登录请求，获取用户 ID
      axios
        .post('http://localhost:3001/login', {
          username: loginForm.value.username,
          password: loginForm.value.oldpassword,
        })
        .then((loginRes) => {
          console.log(loginRes)
          const userId = loginRes.data.data.data.id
          const token = loginRes.data.token // 获取登录返回的令牌
          if (userId) {
            // 使用获取到的 ID 进行用户信息更新
            axios
              .put(
                'http://localhost:3001/updateuser',
                {
                  id: userId,
                  userObj: {
                    password: loginForm.value.password,
                  },
                },
                {
                  headers: {
                    Authorization: `Bearer ${token}`, // 添加 Authorization 头
                  },
                },
              )
              .then((updateRes) => {
                if (updateRes.status === 200) {
                  ElMessage.success('密码修改成功')
                  router.push('/login')
                } else {
                  ElMessage.error('密码修改失败，请稍后重试')
                }
              })
              .catch((updateError) => {
                console.error('更新用户信息出错:', updateError)
                ElMessage.error('更新用户信息出错，请稍后重试')
              })
          } else {
            ElMessage.error('未获取到用户ID，请检查登录信息')
          }
        })
        .catch((loginError) => {
          console.error('登录请求出错:', loginError)
          ElMessage.error('登录请求出错，请检查用户名和密码')
        })
    } else {
      console.log('error submit!!')
      return false
    }
  })
}

const resetForm = () => {
  loginForm.value = {
    username: '',
    oldpassword: '',
    password: '',
    password2: '',
  }
  if (loginFormRef.value) {
    loginFormRef.value.resetFields()
  }
  router.push('/login')
}
</script>

<style lang="scss" scoped>
.changePassword {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url('images/bg.png');
  background-size: cover;

  .changpasswordBox {
    display: flex;
    background-color: #fff;
    padding: 20px;
    margin: auto;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
    border-radius: 10px;
    flex-direction: column;
    align-items: center;
    gap: 20px;

    .login-box1 {
      width: 300px;

      .login-title {
        text-align: center;
        margin-bottom: 20px;
      }

      .el-form-item {
        width: 240px;

        .el-input {
          width: 100%;
        }
      }
    }

    .PasswordBtn {
      display: flex;
      gap: 20px;
      justify-content: center;
      align-items: center;

      .el-button {
        width: 80px;
        height: 30px;
      }
    }
  }
}
</style>
